
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import view.UsuarioDTO;
import controller.Sistema;

public class Login extends HttpServlet 
{
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(req, resp);	
	}

	 public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
	 {	
	 	String action = req.getParameter("action");
		String msg="";
		String msgErr="";			
        String page = "index.jsp";	        
        UsuarioDTO tempUsr = (UsuarioDTO)req.getSession().getAttribute("usr");                                      
        if ((tempUsr==null || tempUsr.getId()==0) && !"executeLogin".equals(action))
        {
        	action="autenticar";       
        }                
        
		if ("executeLogin".equals(action))
		{
	    	UsuarioDTO usr = Sistema.getInstancia().autenticarUsuario(req.getParameter("usuario"), req.getParameter("passwd"));
	    	if (usr!=null &&usr.getId()>0)
	    	{
	    		req.getSession().setAttribute("usr", usr);	
	    		req.getSession().setAttribute("nombreUsuario", usr.getNombre() + ", " + usr.getApellido());
	    		req.setAttribute("action", "principal");
	    		page = "principal.jsp";		    			    	
	    	}
	    	else
	    	{
	    		page = "login.jsp";		    		
	    		req.setAttribute("msgErr", "Los datos ingresados no son correctos");
	    	}	    			    
		}
    	else if ("principal".equals(action))
    	{
    		page = "principal.jsp";
    	}
    	else if ("logout".equals(action))
    	{
    			
    		page = "login.jsp";
    	} 		
    	else if ("autenticar".equals(action))
    	{
    		req.getSession().setAttribute("usr", null);
    		page = "login.jsp";
    	}			
 
		RequestDispatcher dispatcher = req.getRequestDispatcher(page);
		dispatcher.forward(req, resp);	 
	 }
	    protected void dispatch(String page, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	    {
	        if (page != null)
	        {
	            RequestDispatcher rd = request.getRequestDispatcher(page);
	            rd.forward(request, response);
	        }
	    }  
}